package com.newenergy.wisehome.gateway.device;


import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.StorageHelper;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.data.bean.BLDeviceInfo;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.gateway.common.BLCommonUtils;
import com.newenergy.wisehome.gateway.common.BLModelUtil;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.fragment.BaseFragment;
import com.newenergy.wisehome.ui.widget.LoaddingDialogUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.family.params.BLFamilyAllInfo;
import cn.com.broadlink.family.params.BLFamilyDeviceInfo;
import cn.com.broadlink.family.params.BLFamilyInfo;
import cn.com.broadlink.family.params.BLFamilyModuleInfo;
import cn.com.broadlink.family.result.BLModuleControlResult;
import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;
import cn.com.broadlink.sdk.interfaces.controller.BLDeviceScanListener;
import cn.com.broadlink.sdk.param.controller.BLDeviceConfigParam;
import cn.com.broadlink.sdk.result.controller.BLDeviceConfigResult;

/**
 * A simple {@link Fragment} subclass.
 */
public class PairDeviceFragment extends BaseFragment {

    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.et_name)
    TextInputEditText mEtName;
    @BindView(R.id.et_pwd)
    TextInputEditText mEtPwd;
    @BindView(R.id.btn_pair)
    Button mBtnPair;
    @BindView(R.id.btn_eye)
    ToggleButton mBtnPwdToggle;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private AsyncTask<BLDeviceConfigParam, Void, BLDeviceConfigResult> mPairTask;
    private Dialog mLoadingDialog;
    private Map<String, BLDeviceInfo> mDeviceInfoMap = new HashMap();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_pair_device;
    }

    @Override
    public void init(View rootView) {
        mTvPage.setText("配置网关");
        initWiFiSSIDView();
        initListener();
        mBtnPwdToggle.setChecked(false);

    }

    @Override
    public void onResume() {
        super.onResume();
        mDeviceInfoMap.clear();
        BLDeviceInfoDao infoDao = new BLDeviceInfoDao(getContext());
        List<BLDeviceInfo> deviceInfos = infoDao.getTypeDevice(0);
        if (deviceInfos != null && deviceInfos.size() > 0) {
            for (BLDeviceInfo deviceInfo : deviceInfos) {
                mDeviceInfoMap.put(deviceInfo.getDid(), deviceInfo);
            }
        }
    }

    private void initListener() {
        mBtnPwdToggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //如果选中，显示密码
                mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //隐藏密码
                mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });
    }

    @OnClick({R.id.btn_pair, R.id.btn_back, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_pair:
                configDnaDevice(3);
                break;
        }
    }

    private void configDnaDevice(int version) {
        boolean wifiConnect = BLCommonUtils.isWifiConnect(getContext());
        boolean network = BLCommonUtils.checkNetwork(getContext());
        if (wifiConnect && network) {
            String ssid = mEtName.getText().toString();
            String password = mEtPwd.getText().toString();
            if (TextUtils.isEmpty(ssid) || TextUtils.isEmpty(password)) {
                toast("WiFi账号或密码并不能为空");
                return;
            }
            String wifissid = BLCommonUtils.getWIFISSID(getContext());
            if (!ssid.equals(wifissid)) {
                toast("WiFi账号不是当前的连接的WiFi");
                return;
            }
            StorageHelper.setWifiSSID(ssid);
            StorageHelper.setWifiPwd(password);

            BLDeviceConfigParam configParam = new BLDeviceConfigParam();
            configParam.setSsid(ssid);
            configParam.setPassword(password);
            configParam.setVersion(version);
            mLoadingDialog = LoaddingDialogUtils.createLoadingDialog(getContext(), "正在配置网关，请稍等。。。。");
            MyThreadManager.getInstance().doTask(() -> {
                BLDeviceConfigResult result = BLLet.Controller.deviceConfig(configParam, 6 * 1000);
                if (result != null) {
                    Log.i(TAG, "configDnaDevice: result succeed = " + result.succeed() + "  error =" + result.getError() + "  msg =" + result.getMsg());
                }
            });
            startProbe();
            toast("正在进行配网，请稍等。。。");
        } else {
            toast("请连接WIFI或者网络不可用");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    //显示当前手机所连接的SSID
    public void initWiFiSSIDView() {
        boolean wifiConnect = BLCommonUtils.isWifiConnect(getContext());
        if (wifiConnect) {
            String wifissid = BLCommonUtils.getWIFISSID(getContext());
            if (!TextUtils.isEmpty(wifissid)) {
                mEtName.setText(wifissid);
                String wifiSSID = StorageHelper.getWifiSSID();
                if (wifissid.equals(wifiSSID)) {
                    String wifiPwd = StorageHelper.getWifiPwd();
                    mEtPwd.setText(wifiPwd);
                }
            }
        }
    }

    private void startProbe() {
        Log.i(TAG, "startProbe: ");
        BLLet.Controller.startProbe(2 * 1000);
        BLLet.Controller.setOnDeviceScanListener(new BLDeviceScanListener() {
            @Override
            public void onDeviceUpdate(BLDNADevice device, boolean isNewDevice) {
                Log.i(TAG, "BLDNADevice: " + device.toJSONString());
                Log.i(TAG, "onDeviceUpdate: isNewDevice = " + isNewDevice + " device = " + device.getName());
                BLDeviceInfo deviceInfo = BLModelUtil.toBLDeviceInfo(device);
                Log.i(TAG, "onDeviceUpdate: deviceInfo =" + deviceInfo.toString());
                if (true) {
                    BLLet.Controller.stopProbe();
                    BLLet.Controller.deviceConfigCancel();
                    mHandler.post(() -> foundDnaDevice(device, isNewDevice));
                }
            }
        });
    }


    private void foundDnaDevice(BLDNADevice device, boolean isNewDevice) {
        LoaddingDialogUtils.closeDialog(mLoadingDialog);
        if (true) {
            updateDnaDeviceKey(device, isNewDevice);
        }
    }

    private void updateDnaDeviceKey(BLDNADevice device, boolean isNewDevice) {
        Log.i(TAG, "updateDnaDeviceKey: ");
        String did = device.getDid();
        //!mDeviceInfoMap.containsKey(did)
        if (true) {
            BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(device);
            blDeviceInfo.setBlType(0);
            BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
            familyManager.addLocalDevice(device);
            familyManager.updateBLDeviceInfo(blDeviceInfo);
            mDeviceInfoMap.put(did, blDeviceInfo);
            Log.i(TAG, "doBack BindFamilyFragment: ");
            startWithPop(BindFamilyFragment.newInstance(1));
            return;
        } else {
            BLDeviceInfo deviceInfo = mDeviceInfoMap.get(did);
            Log.i(TAG, "updateDnaDeviceKey: deviceInfo = " + deviceInfo.toString());
            String aeskey = device.getKey();
            int terminalId = device.getId();
            boolean isUpdate = !deviceInfo.getKey().equals(aeskey) ||
                    (deviceInfo.getTerminalId() != terminalId);
            if (!isUpdate) {
                return;
            }
            boolean state = BLLocalFamilyManager.getInstance().checkAppState();
            if (!state) {
                return;
            }
            BLLet.Controller.addDevice(device);
            deviceInfo.setKey(aeskey);
            deviceInfo.setId(terminalId);
            String familyId = deviceInfo.getFamilyId();
            if (TextUtils.isEmpty(familyId)) {
                return;
            }
            Family family = new FamilyDao(getContext()).getById(familyId);
            if (family == null || TextUtils.isEmpty(family.getBlFamilyId())) {
                doBack();
                return;
            }
            String blFamilyId = family.getBlFamilyId();
            BLDeviceInfoDao infoDao = new BLDeviceInfoDao(getContext());
            List<BLDeviceInfo> familyBLDeviceInfos = infoDao.getFamilyBLDeviceInfos(familyId, 1);
            if (familyBLDeviceInfos != null && familyBLDeviceInfos.size() > 0) {
                MyThreadManager.getInstance().doTask(() -> {
                    BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
                    BLFamilyAllInfo familyAllInfo = familyManager.queryBLFamilyAllInfoTask(blFamilyId);
                    if (familyAllInfo == null || familyAllInfo.getDeviceInfos().size() < 1) {
                        return;
                    }
                    BLFamilyInfo familyInfo = familyAllInfo.getFamilyInfo();
                    List<BLFamilyDeviceInfo> deviceInfos = familyAllInfo.getDeviceInfos();
                    List<BLFamilyModuleInfo> moduleInfos = familyAllInfo.getModuleInfos();
                    if (moduleInfos == null || moduleInfos.size() < 1) {
                        return;
                    }
                    BLFamilyModuleInfo moduleInfo = moduleInfos.get(0);
                    for (int i = 0; i < deviceInfos.size(); i++) {
                        BLFamilyDeviceInfo familyDeviceInfo = deviceInfos.get(i);
                        familyDeviceInfo.setAeskey(aeskey);
                        familyDeviceInfo.setTerminalId(terminalId);
                        BLModuleControlResult result = BLFamily.addModuleToFamily(moduleInfo, familyInfo, familyDeviceInfo, null);
                        familyManager.showBLResultLog(result, "更新设备key和ID");
                    }
                    infoDao.addOrUpdate(deviceInfo);
                    for (BLDeviceInfo familyBLDeviceInfo : familyBLDeviceInfos) {
                        familyBLDeviceInfo.setKey(aeskey);
                        familyBLDeviceInfo.setTerminalId(terminalId);
                    }
                    familyManager.addSdkDevices(familyBLDeviceInfos);
                    infoDao.update(familyBLDeviceInfos);
                    Log.i(TAG, "updateDnaDeviceKey: deviceInfo = " + deviceInfo.toString());
                    mHandler.post(() -> {
                        toast("更新设备完成");
                    });
                });
            }
        }
    }

}

